package com.mlamp.demo.web.controller.base;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


public class BaseController<T> {
	
	   
	public static final String UPLOAD_PATH="/upload/";
	private static Logger log = Logger.getLogger(BaseController.class);
	
	public static final String FILE_UPLOAD_PATH="D://upload";
	
	
	/**
	 * springmvc 文件获取
	 * @param req
	 * @return
	 */
	public List<MultipartFile> extractUploadFile(HttpServletRequest req) {
		List<MultipartFile> list = new ArrayList<MultipartFile>();
		if ((req instanceof MultipartHttpServletRequest) == false) {
			return list;
		}
		MultipartHttpServletRequest multiReq = (MultipartHttpServletRequest) req;
		Iterator<String> fileNameIter = multiReq.getFileNames();
		while (fileNameIter.hasNext()) {
			MultipartFile file = multiReq.getFile(fileNameIter.next());
			if (!file.isEmpty()) {
//				log.debug("Upload file[" + file.getOriginalFilename() + "] \n"
//						+ "Length: " + file.getSize() + "bytes \n"
//						+ "ContentType:" + file.getContentType());
				list.add(file);
			}
		}
		return list;
	}
	
	public Map<String, Object> upload(HttpServletRequest request) {
		List<MultipartFile> files = this.extractUploadFile(request);
		Map<String, Object> objects = new HashMap<String, Object>();
		if (files!=null&&files.size()>0) {
			for (MultipartFile mFile : files) {
				if(mFile.getSize()<54485760){
					///if (validateUploadFileType(mFile)) {
						
						String fileRealPathdir="";
						try {
							//fileRealPathdir =request.getSession().getServletContext().getRealPath(UPLOAD_PATH) ;
							fileRealPathdir=FILE_UPLOAD_PATH;
						} catch (Exception e1) {
							e1.printStackTrace();
						}
						String fileExt = getExt(mFile);
						String fileName =UUID.randomUUID().toString() + "."+ fileExt;
						File fileSaveDir = new File(fileRealPathdir);
						String filePath=fileName;
						try {
							saveFile(fileSaveDir, fileName, mFile.getBytes());
							objects.put("fileName", fileName);
							objects.put("filePath", filePath);
						} catch (IOException e) {
							log.error("IO异常", e);
						} catch (FileUploadException e) {
							log.error("文件下载异常", e);
						} catch (Exception e) {
							log.error("异常", e);
						}
//					}else{
//						objects.put("type", "error");
//					}
				}else{
					objects.put("size", "error");
				}
				
			}
		}
		return objects;
	}
	
	/**
	 * 保存文件到硬盘上
	 * 
	 * @param savedir
	 *            保存文件的文件夹，当不存在时，会自动创建。该参数不能为空。
	 * @param fileName
	 *            欲保存的文件名。该参数不能为空。
	 * @param data
	 * @throws FileUploadException
	 */
	public static void saveFile(File savedir, String fileName, byte[] data)
			throws FileUploadException {
		Assert.notNull(savedir, "savedir不能为空");
		Assert.hasText(fileName, "fileName不能为空");

		if (!savedir.exists()) {
			savedir.mkdirs();// 如果目录不存在就创建
		}
		// 根据file文件进行构造
		File file = new File(savedir, fileName);
		try {
			FileOutputStream fileoutstream = new FileOutputStream(file);
			fileoutstream.write(data);
			fileoutstream.close();
		} catch (FileNotFoundException e) {
			throw new FileUploadException("上传文件错误", e);
		} catch (IOException e) {
			throw new FileUploadException("上传文件错误", e);
		}
	}
	
	
	/**
	 * 获取文件后缀
	 * @param multipartFile
	 * @return
	 */
	public static String getExt(MultipartFile multipartFile) {
		return multipartFile
				.getOriginalFilename()
				.substring(
						multipartFile.getOriginalFilename().lastIndexOf('.') + 1)
				.toLowerCase();

	}
	
	
	
	
	
	
	
}
